package com.glkj.vipsystem.core.sms.aliyun;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.glkj.vipsystem.common.exception.BizException;
import com.glkj.vipsystem.core.sms.AbstractSmsPlugin;
import com.glkj.vipsystem.core.sms.ISmsSendEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 阿里云sms插件
 */
@Slf4j
@Component("AliyunSmsPlugin")
public class AliyunSmsPlugin extends AbstractSmsPlugin implements ISmsSendEvent {

    //产品名称:云通信短信API产品,开发者无需替换
    private static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    private static final String domain = "dysmsapi.aliyuncs.com";

    // 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    private static final String accessKeyId = "LTAI4Fj6NWA9fpSEfKhuvkJx";
    private static final String accessKeySecret = "EZNAtTt0Xl41lLi6h77nF1HE1gNfEN";
    /**
     * 签名
     */
    private static final String sign_name = "引弓科技";

    /**
     * 为短信插件定义唯一的id
     *
     * @return id
     */
    @Override
    public String getId() {
        return "AliyunSmsPlugin";
    }

    /**
     * 定义插件名称
     *
     * @return 名称
     */
    @Override
    public String getName() {
        return "阿里云短信网关插件";
    }

    /**
     * 发送短信事件
     *
     * @param phone   手机号
     * @param content 发送内容
     * @param param   其它参数
     * @return 是否发送成功
     */
    @Override
    public boolean onSend(String phone, String content, Map param) {
        DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", sign_name);
        String template_code = param.get("template_code").toString();
        request.putQueryParameter("TemplateCode", template_code);
        String[] params = AliyunSmsTemplate.getParams(template_code);
        request.putQueryParameter("TemplateParam", getContent(params, param));
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            log.debug("阿里云短信发送结果:{}", data);
            JSONObject jsonObject = JSONObject.parseObject(data);
            if ("OK".equals(jsonObject.getString("Code"))) {
                return true;
            } else {
                log.error("短信发送失败:{}", jsonObject.getString("Message"));
                throw new BizException("短信发送失败:" + jsonObject.getString("Message"));
            }
        } catch (ClientException e) {
            log.error("短信发送失败:code-【{}】,message-【{}】", e.getErrCode(), e.getErrMsg());
            throw new BizException("短信发送失败:code-【" + e.getErrCode() + "】,message-【" + e.getErrMsg() + "】");
        }
    }

    private static String getContent(String[] params, Map param) {
        StringBuilder content = new StringBuilder("{");
        int length = params.length;
        for (int i = 0; i < length - 1; i++) {
            String smsParam = params[i];
            content.append("\"" + smsParam + "\":");
            content.append("\"" + param.get(smsParam).toString() + "\",");
        }
        content.append("\"" + params[length - 1] + "\":");
        content.append("\"" + param.get(params[length - 1]).toString() + "\"");
        content.append("}");
        return content.toString();
    }

}
